Intersection Observer
要素がViewport内に入っているかどうかを監視できるAPI
Intersection Observer API - Web APIs | MDN
#wip
https://www.patterns.dev/posts/import-on-visibility
実例
https://uhyo.github.io/footnotes-view/
脚注がついて来るやつ
Server ActionsでInfinite Scroll
https://developer.mozilla.org/ja/docs/Web/API/Intersection_Observer_API
reactのdocsでみた
GPT-4.icon
code:javascript
const observer = new IntersectionObserver((entries, observer) => {
//
}, options);
entries
IntersectionObserverEntryの配列
監視対象の要素の状態を表すオブジェクトのリスト
IntersectionObserverEntryのプロパティ
table:table
target 監視している要素 (Element)
isIntersecting true(可視範囲内)、false(範囲外)
intersectionRatio 指定した threshold に対する交差割合(0.0~1.0)
boundingClientRect target の境界ボックス情報(DOMRect)
rootBounds root(監視基準要素)の境界ボックス
time 交差が発生した時間(DOMHighResTimeStamp)
observer
IntersectionObserver インスタンス
observe や unobserve などのメソッドを持つ。
既に処理済みの要素を 監視解除 するのに使う。
使用例
code:javascript
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log(${entry.target.id} が表示された!);
observer.unobserve(entry.target); // 一度見えたら監視を解除
}
});
});
const target = document.querySelector("#myElement");
observer.observe(target);
options
code:javascript
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log("要素が見えた!", entry.target);
}
});
}, {
root: null, // ビューポートを基準に監視
rootMargin: "0px", // 監視範囲のマージン
threshold: 0.5 // 50% 以上見えたら反応
});
threshold を 0~1の範囲 で指定すると、何%見えたら反応するか調整できる。
rootMargin を 負の値 にすると、スクロール前に先読みできる。